﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace Molen_Ameland
{
    public partial class Form1 : Form
    {       
        private const int WM_CLOSE = 16;
        private const int BN_CLICKED = 245;
        public const int WM_LBUTTONDOWN = 0x0201;
        public const int WM_LBUTTONUP = 0x0202;
        public const int WM_SETTEXT = 0x000C;
        static Timer oneSecond;
        static Timer animationTime;
        int count = 1;
        int image = 0;
        string logfile;
        string[] windMillAnimation;
        
        /// <summary>
        /// Required designer variable.
        /// </summary>

        /// <summary>
        /// The FindWindow API
        /// </summary>
        /// <param name="lpClassName">the class name for the window to search for</param>
        /// <param name="lpWindowName">the name of the window to search for</param>
        /// <returns></returns>
        [DllImport("User32.dll")]
        public static extern Int32 FindWindow(String lpClassName, String lpWindowName);

        /// <summary>
        /// The SendMessage API
        /// </summary>
        /// <param name="hWnd">handle to the required window</param>
        /// <param name="msg">the system/Custom message to send</param>
        /// <param name="wParam">first message parameter</param>
        /// <param name="lParam">second message parameter</param>
        /// <returns></returns>
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int SendMessage(int hWnd, int msg, int wParam, IntPtr lParam);

        /// <summary>
        /// The FindWindowEx API
        /// </summary>
        /// <param name="parentHandle">a handle to the parent window </param>
        /// <param name="childAfter">a handle to the child window to start search after</param>
        /// <param name="className">the class name for the window to search for</param>
        /// <param name="windowTitle">the name of the window to search for</param>
        /// <returns></returns>
        [DllImport("user32.dll", SetLastError = true)]
        public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle);
        /// <summary>
        /// 
        /// </summary>
        /// <param name="hwnd"></param>
        /// <param name="lpString"></param>
        /// <returns></returns>
        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern bool SetWindowText(IntPtr hwnd, String lpString);
        [DllImport("User32.dll", EntryPoint = "PostMessageA")]
        static extern bool PostMessage(IntPtr hWnd, uint msg, int wParam, int lParam);

        public Form1()
        {
            windMillAnimation = new string [] { "frame1.png", "frame2.png", "frame3.png", "frame4.png" };
            InitializeComponent();
            //get the log path + filename
            logfile = Data.getPath() + "log.txt";
            //Use the Form1_KeyDown method when a key is pressed
            this.KeyDown += Form1_KeyDown;
            this.KeyPreview = true;
        }
        /// <summary>
        /// This method is called when the start button is clicked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Start_Click(object sender, EventArgs e)
        {
            deleteLog();
            int hwnd = 0;
            IntPtr hwndChild = IntPtr.Zero;
            //Get a handle for the Calculator Application main window
            hwnd = FindWindow(null, "DVE MultiTool 1.2.0 - Build: Aug 14 2013"); 
            if (hwnd == 0)
            {
                //if exepath in settings is empty, ask user to browse for the MultiTool file
                if (Properties.Settings.Default.exepath == "")
                {
                    DialogResult dialogResult = MessageBox.Show("MultiTool moet eerst gestart worden! \n\nWilt u MultiTool nu openen?",
                    "Vraag",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question,
                    MessageBoxDefaultButton.Button1);
                    //If user clicked yes to question dialog
                    if (dialogResult == DialogResult.Yes)
                    {
                        //User clicked "Open" in the open file dialog
                        if (OpenMultitooldialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        {
                            ProcessStartInfo multitoolprocess = new ProcessStartInfo(OpenMultitooldialog.FileName);
                            multitoolprocess.WindowStyle = ProcessWindowStyle.Minimized;
                            Process.Start(multitoolprocess);
                        }
                    
                    }
                    else
                    {
                        //User clicked no, do nothing
                    }
                }
                else
                {
                    //If it's not empty, try to start multitool minimized using the saved setting
                    try
                    {
                        ProcessStartInfo multitoolprocess = new ProcessStartInfo(Properties.Settings.Default.exepath);
                        multitoolprocess.WindowStyle = ProcessWindowStyle.Minimized;
                        Process.Start(multitoolprocess);
                    }
                    //if it cannot be started using the saved setting, clear this setting and re-run this method (so the user can browse for it)
                    catch
                    {
                            Properties.Settings.Default.exepath = "";
                            Properties.Settings.Default.Save(); // saves the settings
                            Start_Click(sender, e);
                    }
                    finally
                    {
                        StartTimer();//Denk hier om...
                        start_animation();
                    }
                }
            }
            else
            {               
                start_animation();
                StartTimer();
            }



        }
        private void Close_Click(object sender, EventArgs e)
        {
            int hwnd = 0;

            //Get a handle for the Calculator Application main window
            hwnd = FindWindow(null, "DVE MultiTool 1.2.0 - Build: Aug 14 2013");

            //send WM_CLOSE system message
            if (hwnd != 1)
            {
                SendMessage(hwnd, WM_CLOSE, 0, IntPtr.Zero);
            }
            //After closing MultiTool, close the c# application
            Application.Exit();
        }
        /// <summary>
        /// Sets screen to Fullscreen and back when the button is clicked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Fullscreen_Click(object sender, EventArgs e)
        {
                this.TopMost = true;
                this.FormBorderStyle = FormBorderStyle.None;
                this.WindowState = FormWindowState.Maximized;
                FullscreenButton.Hide();
                CloseButton.Hide();
        }
        /// <summary>
        /// Starts the timer...
        /// </summary>
        void StartTimer()
        {
            oneSecond = new Timer(); // Set up the timer for 1 second
            oneSecond.Interval = 1000; // Time in milliseconds.
            oneSecond.Tick += Timer_Tick;
            oneSecond.Start();
        }
        /// <summary>
        /// When the Timer runs out this method starts the StartProcess method.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Timer_Tick(object sender, EventArgs e)
        {
            oneSecond.Stop();
            StartProcess();
        } 
        /// <summary>
        /// /// Displays the data on screen through labels.
        /// </summary>
        void StartProcess()
        {
            Data p = new Data(logfile);
            IFormatProvider myFormatProvider = new CultureInfo("nl").NumberFormat;
            object buffer = p.getData(count);
            VoltageLabel.Text = "Voltage: " + p.getData(count).voltage.ToString(myFormatProvider);//p
            PowerLabel.Text = "Power: " + p.getData(count).power.ToString(myFormatProvider);
            EnergyLabel.Text = "Energy: " + p.getData(count).energy.ToString(myFormatProvider);
            TempLabel.Text = "Temp: " + p.getData(count).temperature.ToString(myFormatProvider);
            Windspeed1Label.Text = "Wind Speed 1: " + p.getData(count).windspeed1.ToString(myFormatProvider);
            Windspeed2Label.Text = "Wind Speed 2: " + p.getData(count).windspeed2.ToString(myFormatProvider);
            FrequencyLabel.Text = "Frequency: " + p.getData(count).frequency.ToString(myFormatProvider);
            count++;
            StartTimer();
            StartButton.Hide(); // process started, hide the start button
        }
        /// <summary>
        /// Method that responds to keypresses
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                this.TopMost = false;
                this.FormBorderStyle = FormBorderStyle.Sizable;
                this.WindowState = FormWindowState.Normal;
                FullscreenButton.Text = "Fullscreen";
                CloseButton.Show();
                FullscreenButton.Show();
                // prevent child controls from handling this event as well
                e.SuppressKeyPress = true;
            }
            //When F5 is pressed, display a help popup
            else if (e.KeyCode == Keys.F1)
            {
                MessageBox.Show("F1\t=\tHelp\nF5\t=\tStart\nF12\t=\tFullscreen\nESC\t=\tWindow mode\n\n\n\nThom Wouda\nEden Cox\nNHL Hogeschool 2014",
                "Help",
                MessageBoxButtons.OK,
                MessageBoxIcon.Information ,
                MessageBoxDefaultButton.Button1);
                e.SuppressKeyPress = true;
            }
            //When F5 is pressed, start process
            else if (e.KeyCode == Keys.F5)
            {
                Start_Click(sender, e);
                e.SuppressKeyPress = true;
            }
            //When F12 is pressed, go fullscreen
            else if (e.KeyCode == Keys.F12)
            {
                Fullscreen_Click(sender, e);
                e.SuppressKeyPress = true;
            }
        }
        /// <summary>
        /// Starts the animation timer for the windmill
        /// </summary>
        public void start_animation()
        {
            animationTime = new Timer(); // Set up the timer for 1 second
            animationTime.Interval = 100; // Time in milliseconds.
            animationTime.Tick += AnimationTimer_Tick;
            animationTime.Start();
        }
        /// <summary>
        /// As soon as the timer time has passed it changes the displayed image and restarts the timer
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AnimationTimer_Tick(object sender, EventArgs e)
        {
            animationTime.Stop();
            changeImage();
            start_animation();

        }
        /// <summary>
        /// this method changes the image displayed.
        /// </summary>
        void changeImage()
        {
            image++;
            if (image == 4)
            {
                image = 0;
            }
            pictureBox1.Load(Path.Combine(Environment.CurrentDirectory, @"..\..\Resources\" + windMillAnimation[image]));
        }
        /// <summary>
        /// This method deletes the log.txt file
        /// </summary>
        void deleteLog()
        {
            if (File.Exists(logfile))
            {
                File.Delete(logfile);
            }
        }
        public void saveLogFile()
        {
            int hwnd = 0;
            hwnd = FindWindow(null, "DVE MultiTool 1.2.0 - Build: Aug 14 2013");

            IntPtr hwndChild = IntPtr.Zero;
            //Get a handle for the "Log" button
            hwndChild = FindWindowEx((IntPtr)hwnd, IntPtr.Zero, null, "");
            if (hwndChild != null)
            {
                hwndChild = FindWindowEx((IntPtr)hwndChild, IntPtr.Zero, null, "Monitor");
                if (hwndChild != null)
                {
                    hwndChild = FindWindowEx((IntPtr)hwndChild, IntPtr.Zero, null, "Data Logger");
                    if (hwndChild != null)
                    {
                        hwndChild = FindWindowEx((IntPtr)hwndChild, IntPtr.Zero, null, "Log");
                    }
                }
            }
            //send BN_CLICKED message
            //SendMessage((int)hwndChild, BN_CLICKED, 0, IntPtr.Zero);
            PostMessage(hwndChild, BN_CLICKED, 0, 0);

            System.Threading.Thread.Sleep(250);
            int hwndSave_As_Window = 0;
            hwndSave_As_Window = FindWindow(null, "Save as");
            IntPtr hwndChild_Save_Window = IntPtr.Zero;
            //Get a handle for the "Log" button
            hwndChild_Save_Window = FindWindowEx((IntPtr)hwndSave_As_Window, IntPtr.Zero, "DUIViewWndClassName", "");
            if (hwndChild_Save_Window != null)
            {
                hwndChild_Save_Window = FindWindowEx((IntPtr)hwndChild_Save_Window, IntPtr.Zero, "DirectUIHWND", "");
                if (hwndChild_Save_Window != null)
                {
                    hwndChild_Save_Window = FindWindowEx((IntPtr)hwndChild_Save_Window, IntPtr.Zero, "FloatNotifySink", "");
                    if (hwndChild_Save_Window != null)
                    {
                        hwndChild_Save_Window = FindWindowEx((IntPtr)hwndChild_Save_Window, IntPtr.Zero, "ComboBox", null);
                        if (hwndChild_Save_Window != null)
                        {
                            hwndChild_Save_Window = FindWindowEx((IntPtr)hwndChild_Save_Window, IntPtr.Zero, "Edit", null);
                        }
                    }
                }
            }

            string msg = logfile;
            IntPtr text = System.Runtime.InteropServices.Marshal.StringToCoTaskMemUni(msg);
            SendMessage((int)hwndChild_Save_Window, WM_SETTEXT, 0, text);
            hwndSave_As_Window = FindWindow(null, "Save as");
            hwndChild_Save_Window = FindWindowEx((IntPtr)hwndSave_As_Window, IntPtr.Zero, null, "&Save");
            SendMessage((int)hwndChild_Save_Window, BN_CLICKED, 0, IntPtr.Zero);
            //SendMessage((int)hwndChild, BN_CLICKED, 0, IntPtr.Zero);
            System.Threading.Thread.Sleep(500);
            PostMessage(hwndChild, BN_CLICKED, 0, 0);
            System.Threading.Thread.Sleep(500);
        }
    }
}
